package codegenerator.generator;

import java.util.List;

import baytony.util.Util;
import codegenerator.CodeGeneratorException;
import codegenerator.ColumnInfo;
import codegenerator.CommonHelper;
import codegenerator.FileBean;
import codegenerator.JavaFileBean;
import codegenerator.TableInfo;

public class DaoGenerator extends JavaGenerator {

	private static final String DAO_JTMP = "dao.jtmp";
	private static final String REG_EXP = "#\\w+#";
	private static final String DAO = "Dao";
	
	@Override
	public FileBean createInfo(TableInfo table) throws CodeGeneratorException {
		String jtmpContent = super.readJtmp(DAO_JTMP);
		String tableName = table.getName();
		List<String> contentList = CommonHelper.getMatchStrs(jtmpContent, REG_EXP);
		for(int i=0 ; i<contentList.size() ; i++) {
			String content = contentList.get(i);
			switch(i) {
				case 0:
					jtmpContent = jtmpContent.replace(content, generatorHelper.getProjectName());
					break;
				case 1:
					jtmpContent = jtmpContent.replace(content, generatorHelper.getProjectName());
					break;
				case 2:
					jtmpContent = jtmpContent.replace(content, CommonHelper.table2ClassName(tableName));
					break;
				case 3:
					jtmpContent = jtmpContent.replace(content, CommonHelper.table2ClassName(tableName));
					break;
				case 4:
					jtmpContent = jtmpContent.replace(content, this.getPrimaryInfo(table));
					break;
			}
		}
		FileBean result = new JavaFileBean();
		result.setContent(jtmpContent);
		result.setFileName(CommonHelper.table2ClassName(tableName) + DAO);
		result.setPath(generatorHelper.getSrcPath() + "dao/");
		return result;
	}
	
	private String getPrimaryInfo(TableInfo table) {
		List<ColumnInfo> primaryKeys = table.getPrimaryKey();
		if(!Util.isEmptyList(primaryKeys)) {
			if(primaryKeys.size()>1) {
				return CommonHelper.table2ClassName(table.getName()) + "Pk";
			}
			else {
				ColumnInfo primaryKey = primaryKeys.get(0);
				String type = primaryKey.getType();
				return CommonHelper.dbType2JavaType(type);
			}
		}		
		return "";
	}

}
